/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package led;

import com.rapplogic.xbee.api.ApiId;
import com.rapplogic.xbee.api.PacketListener;
import com.rapplogic.xbee.api.XBee;
import com.rapplogic.xbee.api.XBeeAddress64;
import com.rapplogic.xbee.api.XBeeException;
import com.rapplogic.xbee.api.XBeeResponse;
import com.rapplogic.xbee.api.zigbee.ZNetRxResponse;
import com.rapplogic.xbee.api.zigbee.ZNetTxRequest;
import java.io.IOException;
import java.sql.Connection;
import java.util.logging.Level;
import java.util.logging.Logger;


/**
 *
 * @author ubaldoylaura
 */
public class Main {
    
   XBee xbee = new XBee();
   
    INTERFAZ interfaz;
    
    public Main (INTERFAZ instanciaInterfaz){
        interfaz = instanciaInterfaz;
    }
   
    public boolean connect() throws XBeeException, IOException { 
     // replace with port and baud rate of your XBee
        
        xbee.open("/dev/ttyUSB0", 9600);
        System.out.println("[ Conexión XBee OK ]");
      
        
    xbee.addPacketListener(new PacketListener() {
            
        public void processResponse(XBeeResponse remoteRequest) {
           
            if (remoteRequest.getApiId() == ApiId.ZNET_RX_RESPONSE) {
                ZNetRxResponse rxPacket = (ZNetRxResponse) remoteRequest;
                System.out.println(rxPacket);
                try {
                procesaPaquete(rxPacket);
                System.out.println("Comprobacion4.2 ");
                }catch (IOException ex) {
                 Logger.getLogger(Connection.class.getName()).log(Level.SEVERE, null, ex);
                }
             }
         }
    });
     return true;
    }
    public void sendPacket(int[] payload, XBeeAddress64 address) throws XBeeException {
       ZNetTxRequest request = new ZNetTxRequest(address, payload); // Creates a request to send a packet
       System.out.println(request);
       xbee.sendAsynchronous(request); // Sends the request without
       System.out.println("Comprobacion3: ENVIA");
       // TxStatusResponse
   }
    
  
    void procesaPaquete(ZNetRxResponse rxPacket) throws IOException {
         
     int temp = (0x100*rxPacket.getData()[0]+rxPacket.getData()[1]);
     System.out.println("RECIBE TEMPERATURA");
     interfaz.actualizarDatos(temp);
        
    }
  
    
    
    
}
